﻿using PLCS.Domain.Shared.Tasks;

namespace PLCS.Domain.Tasks;

public class Instruction : BaseEntity
{
    /// <summary>
    /// 指令号
    /// </summary>
    public int InstructionNo { get; set; }

    /// <summary>
    /// 任务Id
    /// </summary>
    public TaskModel? Task { get; set; }

    public Guid? TaskId { get; set; }

    /// <summary>
    /// 执行设备编号
    /// </summary>
    public string EquipmentNo { get; set; }

    /// <summary>
    /// 执行所属工位编号
    /// </summary>
    public string? ContainStationNo { get; set; }

    /// <summary>
    /// 指令类型
    /// </summary>
    public InstructionType InstructionType { get; set; }

    /// <summary>
    /// 启动时坐标
    /// </summary>
    public int InitalPos { get; set; }

    /// <summary>
    /// 坐标行走用
    /// </summary>
    public int MovePos { get; set; }

    /// <summary>
    /// 起始位
    /// </summary>
    public string? StartPos { get; set; }

    /// <summary>
    /// 目标位
    /// </summary>
    public string? EndPos { get; set; }

    /// <summary>
    /// 托盘类型
    /// </summary>
    public TrayType TrayType { get; set; }

    /// <summary>
    /// 指令状态
    /// </summary>
    public Shared.Tasks.InstructionStatus Status { get; set; }

    /// <summary>
    /// 未执行原因
    /// </summary>
    public string? UnexecutedReason { get; set; }

    public Instruction()
    {
    }

    public Instruction(int instructionNo, Guid? taskId, string equipmentNo, InstructionType instructionType, string? startPos = null, string? endPos = null, TrayType trayType = default, string containStationNo = null)
    {
        InstructionNo = instructionNo;
        TaskId = taskId;
        EquipmentNo = equipmentNo;
        InstructionType = instructionType;
        StartPos = startPos;
        EndPos = endPos;
        Status = Shared.Tasks.InstructionStatus.未执行;
        TrayType = trayType;
        ContainStationNo = containStationNo;
    }

    public Instruction SetMovePos(int movePos)
    {
        MovePos = movePos;
        return this;
    }

    public Instruction ChangeStatus(Shared.Tasks.InstructionStatus status)
    {
        Status = status;
        if (status == Shared.Tasks.InstructionStatus.已完成)
            AddLocalEvent(new InstructionFinshEvent()
            {
                Id = Id,
                InstructionNo = InstructionNo,
                TaskId = TaskId,
                EndPos = EndPos,
                EquipmentNo = EquipmentNo,
                StartPos = StartPos,
                InstructionType = InstructionType,
                TrayType = TrayType,
                InitalPos = InitalPos,
                MovePos = MovePos,
            });
        return this;
    }
}